package com.example.maruko_course_backend.services.impl;

import com.example.maruko_course_backend.dto.TranslateDto;
import com.example.maruko_course_backend.services.TranslateService;
import com.example.maruko_course_backend.services.impl.KanjiTranslateApiServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.example.maruko_course_backend.constants.HiraganaConstants.isHiragana;
import static com.example.maruko_course_backend.constants.HiraganaConstants.isKanji;
import static com.example.maruko_course_backend.utils.StringUtil.EMPTY_STR;

@Service
public class TranslateServiceImpl implements TranslateService {
  @Autowired
  private KanjiTranslateApiServiceImpl kanjiTranslateApiServiceImpl;

  @Override
  public List<TranslateDto> splitAndGetTranslateDtos(String sentence) {
    List<TranslateDto> results = getSplitWordWithType(sentence);
    suppTranslateHiraganaForKanjiType(results);
    return results;
  }

  private void suppTranslateHiraganaForKanjiType(List<TranslateDto> results) {
    for (TranslateDto result : results) {
      if (!result.isKanji()) {
        continue;
      }
      result.setTranslatedHiragana(kanjiTranslateApiServiceImpl.callApiForTranslateKanji(result.getOriginWord()));
    }
  }

  public List<TranslateDto> getSplitWordWithType(String sentence) {
    List<TranslateDto> result = new ArrayList<>();
    String hiraganaCombine = EMPTY_STR;
    String kanjiCombine = EMPTY_STR;
    for (int i = 0; i < sentence.length(); i++) {
      String currChar = String.valueOf(sentence.charAt(i));
      if (isKanji(currChar)) {
        kanjiCombine += currChar;
        if (!EMPTY_STR.equals(hiraganaCombine)) {
          result.add(new TranslateDto(hiraganaCombine, false));
          hiraganaCombine = EMPTY_STR;
        }
      }
      if (isHiragana(currChar)) {
        hiraganaCombine += currChar;
        if (!EMPTY_STR.equals(kanjiCombine)) {
          result.add(new TranslateDto(kanjiCombine, true));
          kanjiCombine = EMPTY_STR;
        }
      }
    }
    if (!hiraganaCombine.equals(EMPTY_STR)) {
      result.add(new TranslateDto(hiraganaCombine, false));
    }
    if (!kanjiCombine.equals(EMPTY_STR)) {
      result.add(new TranslateDto(kanjiCombine, true));
    }
    return result;
  }
}
